package com.xzxy.xmlg_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzxy.xmlg_backend.entity.Announcements;
import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.entity.dto.AnnouncementsDto;
import com.xzxy.xmlg_backend.entity.vo.AnnouncementsVo;
import com.xzxy.xmlg_backend.service.IAnnouncementsService;
import com.xzxy.xmlg_backend.service.AnnouncementScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import com.xzxy.xmlg_backend.service.WebSocketService;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 公告表 前端控制器
 * </p>
 *
 * @author 周毅盛
 * @since 2025-06-16
 */
@RestController
@RequestMapping("/announcements")
@Tag(name = "公告管理")
public class AnnouncementsController {

    @Autowired
    private IAnnouncementsService announcementsService;

    @Autowired
    private AnnouncementScheduleService scheduleService;


    @Autowired
    private WebSocketService webSocketService;

    /**
     * 分页查询公告
     * @param announcementsDto
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询公告", description = "分页查询公告信息")
    public Result page(AnnouncementsDto announcementsDto) {
        Page<Announcements> page = new Page<>(announcementsDto.getPage(), announcementsDto.getPageSize());
        LambdaQueryWrapper<Announcements> wrapper = new LambdaQueryWrapper<>();
        
        if (announcementsDto.getTitle() != null && !announcementsDto.getTitle().isEmpty()) {
            wrapper.like(Announcements::getTitle, announcementsDto.getTitle());
        }
        if (announcementsDto.getAuthor() != null && !announcementsDto.getAuthor().isEmpty()) {
            wrapper.like(Announcements::getAuthor, announcementsDto.getAuthor());
        }
        if (announcementsDto.getPublishStatus() != null && !announcementsDto.getPublishStatus().isEmpty()) {
            wrapper.eq(Announcements::getPublishStatus, announcementsDto.getPublishStatus());
        }
        if (announcementsDto.getStartTime() != null) {
            wrapper.ge(Announcements::getPublishTime, announcementsDto.getStartTime());
        }
        if (announcementsDto.getEndTime() != null) {
            wrapper.le(Announcements::getPublishTime, announcementsDto.getEndTime());
        }
        
        wrapper.orderByDesc(Announcements::getCreatedAt);
        
        List<Announcements> list = announcementsService.list(page, wrapper);
        AnnouncementsVo announcementsVo = new AnnouncementsVo();
        announcementsVo.setRows(list);
        announcementsVo.setTotal(page.getTotal());
        return Result.success(announcementsVo);
    }

    /**
     * 根据ID查询公告
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询公告", description = "根据ID查询公告详情")
    public Result getById(@PathVariable Integer id) {
        return Result.success(announcementsService.getById(id));
    }

    /**
     * 新增公告
     * @param announcements
     * @return
     */
    @PostMapping
    @Operation(summary = "新增公告", description = "新增公告信息")
    public Result add(@RequestBody Announcements announcements) {
        announcements.setCreatedAt(LocalDateTime.now());
        announcements.setUpdatedAt(LocalDateTime.now());
        
        // 如果设置了发布时间且状态为暂存，创建定时任务
        if (announcements.getPublishTime() != null && "暂存".equals(announcements.getPublishStatus())) {
            boolean saved = announcementsService.save(announcements);
            if (saved) {
                scheduleService.scheduleAnnouncement(announcements.getId(), announcements.getPublishTime());
                return Result.success("公告已保存，将在指定时间自动发布");
            }
        } else {
            boolean saved = announcementsService.save(announcements);
            if (saved) {
                // 如果公告状态为已发布，立即推送WebSocket消息
                if ("已发布".equals(announcements.getPublishStatus())) {
                    webSocketService.sendNotification("公告发布", announcements.getTitle(), "info");
                }
                return Result.success("公告保存成功");
            }
        }
        return Result.fail("新增公告失败，请稍后再试！");
    }

    /**
     * 修改公告
     * @param announcements
     * @return
     */
    @PutMapping
    @Operation(summary = "修改公告", description = "修改公告信息")
    public Result update(@RequestBody Announcements announcements) {
        announcements.setUpdatedAt(LocalDateTime.now());
        
        // 如果修改了发布时间且状态为暂存，重新创建定时任务
        if (announcements.getPublishTime() != null && "暂存".equals(announcements.getPublishStatus())) {
            boolean updated = announcementsService.updateById(announcements);
            if (updated) {
                // 取消原有定时任务并创建新的
                scheduleService.cancelScheduledAnnouncement(announcements.getId());
                scheduleService.scheduleAnnouncement(announcements.getId(), announcements.getPublishTime());
                return Result.success("公告已更新，将在指定时间自动发布");
            }
        } else {
            boolean updated = announcementsService.updateById(announcements);
            if (updated) {
                // 如果状态改为已发布，取消定时任务并推送WebSocket消息
                if ("已发布".equals(announcements.getPublishStatus())) {
                    scheduleService.cancelScheduledAnnouncement(announcements.getId());
                    webSocketService.sendNotification("公告发布", announcements.getTitle(), "info");
                }
                return Result.success("公告更新成功");
            }
        }
        return Result.fail("修改公告失败，请稍后再试！");
    }

    /**
     * 删除公告
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除公告", description = "删除公告信息")
    public Result delete(@PathVariable List<Integer> ids) {
        // 取消相关的定时任务
        for (Integer id : ids) {
            scheduleService.cancelScheduledAnnouncement(id);
        }
        
        boolean deleted = announcementsService.removeByIds(ids);
        if (deleted) {
            return Result.success("删除成功");
        }
        return Result.fail("删除公告失败，请稍后再试！");
    }

    /**
     * 立即发布公告
     * @param id
     * @return
     */
    @PostMapping("/publish/{id}")
    @Operation(summary = "立即发布公告", description = "立即发布指定公告")
    public Result publishNow(@PathVariable Integer id) {
        Announcements announcement = announcementsService.getById(id);
        if (announcement == null) {
            return Result.fail("公告不存在");
        }
        
        announcement.setPublishStatus("已发布");
        announcement.setPublishTime(LocalDateTime.now());
        announcement.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = announcementsService.updateById(announcement);

        if (updated) {
            // 取消定时任务
            scheduleService.cancelScheduledAnnouncement(id);
            webSocketService.sendNotification("公告发布", announcement.getTitle(), "info");
            return Result.success("公告发布成功");
        }
        return Result.fail("发布失败，请稍后再试！");
    }
}
